package com.xpqh.ksg.modular.sys.service;

import com.alibaba.fastjson.JSON;
import com.xpqh.ksg.common.persistence.dao.KsgSysFileEntityMapper;
import com.xpqh.ksg.common.persistence.model.KsgSysFileEntity;
import common.enums.FilePathEnum;
import common.utils.aliyun.OssFileUploader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class KsgSysFileService {

    @Autowired
    private KsgSysFileEntityMapper fileEntityMapper;

    public KsgSysFileEntity uploadFile(Integer userId, MultipartFile file, FilePathEnum fileType) {
        // 生成唯一文件名
        String fileName = OssFileUploader.generatorFileName();

        // 上传文件到OSS
        String fullFileName = OssFileUploader.multipartFileUpload(file, fileType, fileName);

        // 获取文件MD5
        String fileMd5 = "";
        try (InputStream inputStream = file.getInputStream()) {
            fileMd5 = DigestUtils.md5Hex(inputStream);
        } catch (IOException e) {
            log.error("Error getting file MD5", e);
        }

        // 获取文件元数据
        Map<String, Object> metaMap = new HashMap<>();
        if (file.getContentType() != null && file.getContentType().startsWith("image/")) {
            try (InputStream inputStream = file.getInputStream()) {
                BufferedImage image = ImageIO.read(inputStream);
                if (image != null) {
                    metaMap.put("width", image.getWidth());
                    metaMap.put("height", image.getHeight());
                }
            } catch (IOException e) {
                log.error("Error reading image dimensions", e);
            }
        }
        String fileMeta = JSON.toJSONString(metaMap);

        // 创建文件实体
        KsgSysFileEntity fileEntity = new KsgSysFileEntity();
        fileEntity.setFileId(fileName);
        fileEntity.setFileName(fullFileName);
        fileEntity.setFilePath(fileType.getPath() + fullFileName);
        fileEntity.setFileContentType(file.getContentType());
        fileEntity.setFileExtension(fullFileName.substring(fullFileName.lastIndexOf(".")));
        fileEntity.setFileSize(new BigDecimal(file.getSize()));
        fileEntity.setFilePreview("1");
        fileEntity.setCreateDate(new Date());
        fileEntity.setUserId(userId);
        fileEntity.setFileMd5(fileMd5);
        fileEntity.setFileMeta(fileMeta);

        // 保存到数据库
        fileEntityMapper.insert(fileEntity);

        return fileEntity;
    }
}

